<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Credits Mall - CarbonTrack</title>
  <link rel="icon" href="/img/team.jpg" type="image/JPG">
  
  <!-- CDN References -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
  
  <!-- SF Pro font -->
  <link href="https://fonts.cdnfonts.com/css/sf-pro-display" rel="stylesheet">
  
  <!-- Custom CSS -->
  <link rel="stylesheet" href="./css/ios-design.css">
  <link rel="stylesheet" href="./css/index.css">
  
  <!-- JavaScript libraries -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
  <script src="js/utils.js"></script>
  <script src="js/nav.js"></script>
  
  <style>
    :root {
      --card-bg-light: rgba(255, 255, 255, 0.8);
      --card-bg-dark: rgba(44, 44, 46, 0.8);
      --text-color-light: #000;
      --text-color-dark: #FFFFFF;
      --store-gradient-start: var(--ios-orange);
      --store-gradient-end: var(--ios-pink);
    }
    
    body {
      background-color: var(--ios-secondary-system-background, #F2F2F7);
      color: var(--text-color-light);
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
      position: relative;
      min-height: 100vh;
      transition: background-color 0.3s ease, color 0.3s ease;
    }
    
    /* Frosted glass background effect */
    .frosted-glass {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: -2;
      backdrop-filter: blur(20px);
      -webkit-backdrop-filter: blur(20px);
      background: rgba(255, 255, 255, 0.05);
    }
    
    /* Add ambient glow effects */
    .glow-effect {
      position: fixed;
      width: 300px;
      height: 300px;
      border-radius: 50%;
      filter: blur(50px);
      z-index: -1;
      opacity: 0.5;
      animation: pulse 8s infinite alternate cubic-bezier(0.25, 0.1, 0.25, 1);
    }
    
    .glow-orange {
      top: 10%;
      right: 10%;
      background: radial-gradient(circle, rgba(255, 149, 0, 0.2), transparent 70%);
    }
    
    .glow-pink {
      bottom: 10%;
      left: 5%;
      background: radial-gradient(circle, rgba(255, 45, 85, 0.15), transparent 70%);
      animation-delay: 2s;
    }
    
    @keyframes pulse {
      0% { transform: scale(1) translate(0, 0); opacity: 0.5; }
      50% { transform: scale(1.05) translate(20px, -10px); opacity: 0.7; }
      100% { transform: scale(1) translate(0, 0); opacity: 0.5; }
    }
    
    .store-header {
      background: linear-gradient(135deg, var(--store-gradient-start), var(--store-gradient-end));
      color: white;
      padding: 120px 0 80px;
      text-align: center;
      border-radius: 0 0 24px 24px;
      margin-bottom: 40px;
      position: relative;
      overflow: hidden;
    }
    
    /* Add shimmer effect */
    .store-header::before {
      content: '';
      position: absolute;
      top: -50%;
      left: -50%;
      width: 200%;
      height: 200%;
      background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 60%);
      transform: rotate(30deg);
      animation: shimmer 10s infinite linear;
      pointer-events: none;
    }
    
    @keyframes shimmer {
      0% { transform: translateX(-50%) rotate(0deg); }
      100% { transform: translateX(0%) rotate(360deg); }
    }
    
    .store-header h1 {
      font-weight: 700;
      color: white;
      margin-bottom: 16px;
      position: relative;
      z-index: 2;
    }
    
    .store-header p {
      font-size: 1.2rem;
      opacity: 0.9;
      max-width: 700px;
      margin: 0 auto;
      position: relative;
      z-index: 2;
    }
    
    .user-credits {
      background: linear-gradient(135deg, var(--ios-green), var(--ios-mint));
      color: white;
      border-radius: 24px;
      padding: 24px;
      margin-bottom: 30px;
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
      position: relative;
      overflow: hidden;
    }
    
    .user-credits::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: linear-gradient(135deg, rgba(255,255,255,0.1), transparent 70%);
      pointer-events: none;
    }
    
    .user-credits h2 {
      color: white;
      margin-bottom: 16px;
      font-weight: 700;
      position: relative;
      z-index: 1;
    }
    
    .credits-amount {
      font-size: 2.5rem;
      font-weight: 700;
      margin-bottom: 8px;
      position: relative;
      z-index: 1;
    }
    
    .user-credits p {
      position: relative;
      z-index: 1;
    }
    
    .product-card {
      border-radius: 24px;
      overflow: hidden;
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.06);
      margin-bottom: 30px;
      transition: transform 0.4s var(--animation-timing-apple),
                  box-shadow 0.4s var(--animation-timing-apple);
      background-color: var(--card-bg-light);
      backdrop-filter: blur(20px);
      -webkit-backdrop-filter: blur(20px);
      height: 100%;
    }
    
    .product-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 16px 40px rgba(0, 0, 0, 0.1);
    }
    
    .product-img {
      width: 100%;
      height: 200px;
      object-fit: cover;
      transition: transform 0.4s var(--animation-timing-apple);
    }
    
    .product-card:hover .product-img {
      transform: scale(1.03);
    }
    
    .product-body {
      padding: 24px;
    }
    
    .product-title {
      font-weight: 700;
      margin-bottom: 8px;
      background: linear-gradient(135deg, var(--ios-pink), var(--ios-orange));
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }
    
    .product-description {
      color: var(--ios-gray);
      margin-bottom: 16px;
      height: 48px;
      overflow: hidden;
    }
    
    .product-price {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16px;
    }
    
    .price-tag {
      font-weight: 700;
      font-size: 1.2rem;
      color: var(--ios-green);
    }
    
    .exchange-btn {
      background: linear-gradient(135deg, var(--ios-blue), var(--ios-indigo));
      color: white;
      border: none;
      border-radius: 12px;
      padding: 10px 16px;
      font-weight: 600;
      transition: all 0.3s var(--animation-timing-apple);
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    }
    
    .exchange-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
    }
    
    .section-title {
      font-weight: 700;
      text-align: center;
      margin-bottom: 2rem;
      background: linear-gradient(120deg, var(--ios-orange), var(--ios-pink));
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      position: relative;
      display: inline-block;
    }
    
    .section-title::after {
      content: '';
      position: absolute;
      bottom: -10px;
      left: 50%;
      transform: translateX(-50%);
      width: 80px;
      height: 3px;
      background: linear-gradient(120deg, var(--ios-orange), var(--ios-pink));
      border-radius: 1.5px;
    }
    
    .section-title-container {
      text-align: center;
      margin-bottom: 2rem;
    }
    
    .loading-spinner {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 200px;
    }
    
    /* iOS 风格加载动画 */
    .ios-loader {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      padding: 30px;
      border-radius: 20px;
      backdrop-filter: blur(10px);
      -webkit-backdrop-filter: blur(10px);
      background-color: rgba(255, 255, 255, 0.08);
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);
      transition: all 0.3s var(--animation-timing-apple);
    }
    
    /* 加载动画圆环 */
    .ios-loader-ring {
      position: relative;
      width: 60px;
      height: 60px;
      margin-bottom: 20px;
    }
    
    .ios-loader-ring::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      border-radius: 50%;
      border: 3px solid rgba(0, 122, 255, 0.2);
    }
    
    .ios-loader-ring::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      border-radius: 50%;
      border: 3px solid transparent;
      border-top-color: var(--ios-blue);
      animation: ios-loader-rotate 1.5s linear infinite;
    }
    
    @keyframes ios-loader-rotate {
      0% {
        transform: rotate(0deg);
      }
      100% {
        transform: rotate(360deg);
      }
    }
    
    .ios-loader-dots {
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 16px 0;
    }
    
    .ios-loader-dot {
      width: 10px;
      height: 10px;
      margin: 0 5px;
      border-radius: 50%;
      background: linear-gradient(135deg, var(--ios-blue), var(--ios-indigo));
      opacity: 0;
      transform: scale(0.8);
      animation: ios-loader-pulse 1.5s infinite ease-in-out;
    }
    
    .ios-loader-dot:nth-child(1) {
      animation-delay: 0s;
    }
    
    .ios-loader-dot:nth-child(2) {
      animation-delay: 0.2s;
    }
    
    .ios-loader-dot:nth-child(3) {
      animation-delay: 0.4s;
    }
    
    .ios-loader-text {
      font-size: 16px;
      font-weight: 500;
      margin-top: 8px;
      color: var(--ios-gray);
      opacity: 0.9;
      background: linear-gradient(135deg, var(--ios-blue), var(--ios-indigo));
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      animation: ios-loader-text-pulse 1.5s infinite ease-in-out;
    }
    
    @keyframes ios-loader-pulse {
      0%, 100% {
        opacity: 0.3;
        transform: scale(0.8);
      }
      50% {
        opacity: 1;
        transform: scale(1);
      }
    }
    
    @keyframes ios-loader-text-pulse {
      0%, 100% {
        opacity: 0.7;
      }
      50% {
        opacity: 1;
      }
    }
    
    /* 加载器周围的光晕效果 */
    .ios-loader::after {
      content: '';
      position: absolute;
      width: 150px;
      height: 150px;
      border-radius: 50%;
      background: radial-gradient(circle, rgba(0, 122, 255, 0.1) 0%, transparent 70%);
      z-index: -1;
      animation: ios-loader-glow 2s infinite alternate ease-in-out;
    }
    
    @keyframes ios-loader-glow {
      0% {
        opacity: 0.5;
        transform: scale(0.9);
      }
      100% {
        opacity: 0.8;
        transform: scale(1.1);
      }
    }
    
    .stock {
      padding: 6px 12px;
      border-radius: 10px;
      background-color: rgba(0, 122, 255, 0.1);
      color: var(--ios-blue);
      font-weight: 600;
      font-size: 0.9rem;
      display: inline-block;
    }
    
    /* Theme toggle button */
    .theme-toggle {
      position: fixed;
      right: 20px;
      bottom: 20px;
      width: 50px;
      height: 50px;
      border-radius: 25px;
      background: var(--ios-system-background);
      display: flex;
      justify-content: center;
      align-items: center;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      cursor: pointer;
      z-index: 100;
      transition: all 0.3s var(--animation-timing-apple);
    }
    
    .theme-toggle:hover {
      transform: scale(1.05);
    }
    
    .theme-toggle i {
      font-size: 24px;
      color: var(--ios-gray);
    }
    
    /* Animation classes */
    .fade-in-up {
      animation: fadeInUp 0.6s cubic-bezier(0.25, 0.1, 0.25, 1) forwards;
      opacity: 0;
    }
    
    @keyframes fadeInUp {
      from {
        opacity: 0;
        transform: translateY(20px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }
    
    .delay-1 { animation-delay: 0.1s; }
    .delay-2 { animation-delay: 0.2s; }
    .delay-3 { animation-delay: 0.3s; }
    .delay-4 { animation-delay: 0.4s; }
    .delay-5 { animation-delay: 0.5s; }
    
    /* Dark mode adaptations */
    @media (prefers-color-scheme: dark) {
      body.auto-theme {
        background-color: #1C1C1E;
        color: var(--text-color-dark);
      }
      
      body.auto-theme .product-card {
        background-color: var(--card-bg-dark);
      }
      
      body.auto-theme .product-description {
        color: #AEAEB2;
      }
      
      body.auto-theme .price-tag {
        color: #30D158;
      }
      
      body.auto-theme .stock {
        background-color: rgba(10, 132, 255, 0.2);
        color: #64D2FF;
      }
      
      body.auto-theme .theme-toggle {
        background-color: rgba(44, 44, 46, 0.8);
      }
      
      body.auto-theme .theme-toggle i {
        color: #AEAEB2;
      }
      
      body.auto-theme .section-title::after {
        background: linear-gradient(120deg, #FF9500, #FF2D55);
      }
      
      body.auto-theme p {
        color: rgba(255, 255, 255, 0.8);
      }
      
      body.auto-theme .alert {
        color: #FFFFFF;
      }
      
      body.auto-theme .alert-info {
        background-color: rgba(59, 130, 246, 0.2);
        border-color: rgba(59, 130, 246, 0.3);
      }
      
      body.auto-theme .alert-danger {
        background-color: rgba(239, 68, 68, 0.2);
        border-color: rgba(239, 68, 68, 0.3);
      }
      
      body.auto-theme .ios-loader-text {
        color: #AEAEB2;
      }
      
      body.auto-theme .ios-loader::after {
        background: radial-gradient(circle, rgba(10, 132, 255, 0.15) 0%, transparent 70%);
      }
      
      body.auto-theme .ios-loader {
        background-color: rgba(44, 44, 46, 0.3);
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
      }
      
      body.auto-theme .ios-loader-ring::before {
        border-color: rgba(10, 132, 255, 0.15);
      }
      
      body.auto-theme .ios-loader-ring::after {
        border-top-color: var(--ios-blue);
      }
      
      body.auto-theme .ios-loader-text {
        color: #AEAEB2;
      }
      
      body.auto-theme .ios-loader::after {
        background: radial-gradient(circle, rgba(10, 132, 255, 0.15) 0%, transparent 70%);
      }
    }
    
    /* Manual theme classes */
    body.dark-theme {
      background-color: #1C1C1E;
      color: var(--text-color-dark);
    }
    
    body.dark-theme .product-card {
      background-color: var(--card-bg-dark);
    }
    
    body.dark-theme .product-description {
      color: #AEAEB2;
    }
    
    body.dark-theme .price-tag {
      color: #30D158;
    }
    
    body.dark-theme .stock {
      background-color: rgba(10, 132, 255, 0.2);
      color: #64D2FF;
    }
    
    body.dark-theme .theme-toggle {
      background-color: rgba(44, 44, 46, 0.8);
    }
    
    body.dark-theme .theme-toggle i {
      color: #AEAEB2;
    }
    
    body.dark-theme .section-title::after {
      background: linear-gradient(120deg, #FF9500, #FF2D55);
    }
    
    body.dark-theme p {
      color: rgba(255, 255, 255, 0.8);
    }
    
    body.dark-theme .alert {
      color: #FFFFFF;
    }
    
    body.dark-theme .alert-info {
      background-color: rgba(59, 130, 246, 0.2);
      border-color: rgba(59, 130, 246, 0.3);
    }
    
    body.dark-theme .alert-danger {
      background-color: rgba(239, 68, 68, 0.2);
      border-color: rgba(239, 68, 68, 0.3);
    }
    
    body.dark-theme .ios-loader-text {
      color: #AEAEB2;
    }
    
    body.dark-theme .ios-loader::after {
      background: radial-gradient(circle, rgba(10, 132, 255, 0.15) 0%, transparent 70%);
    }
    
    body.light-theme {
      background-color: #F2F2F7;
      color: var(--text-color-light);
    }
    
    /* 气泡动画效果 */
    .bubble {
      position: absolute;
      width: 16px;
      height: 16px;
      border-radius: 50%;
      background: linear-gradient(135deg, rgba(0, 122, 255, 0.3), rgba(88, 86, 214, 0.1));
      box-shadow: 0 0 10px rgba(0, 122, 255, 0.2);
      animation: bubble-float 3s ease-in infinite;
      opacity: 0;
      z-index: -1;
    }
    
    @keyframes bubble-float {
      0% {
        opacity: 0;
        transform: translateY(0) scale(0.5);
      }
      50% {
        opacity: 0.6;
        transform: translateY(-40px) scale(1);
      }
      100% {
        opacity: 0;
        transform: translateY(-80px) scale(0.5);
      }
    }

    /* Dark Mode Styles for Exchange Confirmation Modal */
    body.dark-mode #exchangeConfirmModal .modal-content {
        background-color: #2d3748; /* Dark background */
        color: #edf2f7; /* Light text */
        border: 1px solid #4a5568; /* Slightly lighter border */
        border-radius: 15px; /* Keep the rounded corners */
    }

    body.dark-mode #exchangeConfirmModal .modal-header {
        background-color: #1a202c; /* Even darker header */
        border-bottom: 1px solid #4a5568;
        border-top-left-radius: 15px;
        border-top-right-radius: 15px;
    }

    body.dark-mode #exchangeConfirmModal .modal-title {
        color: #e2e8f0; /* Light title text */
    }

    body.dark-mode #exchangeConfirmModal .modal-header .close {
        color: #e2e8f0; /* Light close button */
        opacity: 0.7;
        text-shadow: none;
    }
     body.dark-mode #exchangeConfirmModal .modal-header .close:hover {
        opacity: 1;
    }

    body.dark-mode #exchangeConfirmModal .modal-body {
        /* Background is inherited from modal-content */
        color: #edf2f7; /* Ensure body text is light */
    }

     body.dark-mode #exchangeConfirmModal .modal-body strong {
        color: #a0aec0; /* Slightly different color for emphasized text */
    }

    body.dark-mode #exchangeConfirmModal .modal-footer {
        background-color: #2d3748; /* Match modal content background */
        border-top: 1px solid #4a5568;
        border-bottom-left-radius: 15px;
        border-bottom-right-radius: 15px;
    }

    /* Style buttons for dark mode if default bootstrap is too light/dark */
    body.dark-mode #exchangeConfirmModal .modal-footer .btn-secondary {
        background-color: #4a5568;
        border-color: #4a5568;
        color: #e2e8f0;
    }
     body.dark-mode #exchangeConfirmModal .modal-footer .btn-secondary:hover {
        background-color: #2d3748;
        border-color: #2d3748;
    }

    body.dark-mode #exchangeConfirmModal .modal-footer .btn-primary {
        background-color: #3182ce; /* Example blue */
        border-color: #3182ce;
        color: #ffffff;
    }
     body.dark-mode #exchangeConfirmModal .modal-footer .btn-primary:hover {
        background-color: #2b6cb0;
        border-color: #2b6cb0;
    }
     body.dark-mode #exchangeConfirmModal .modal-footer .btn-primary:disabled {
        background-color: #4a5568; 
        border-color: #4a5568;
        opacity: 0.65;
    }
  </style>
</head>
<body class="auto-theme">
<!-- Add frosted glass background -->
<div class="frosted-glass"></div>

<!-- Add ambient glow effects -->
<div class="glow-effect glow-orange"></div>
<div class="glow-effect glow-pink"></div>

<!-- 导航栏容器，将由JavaScript加载 -->
<div id="navbar-container"></div>

<header class="store-header">
  <div class="container">
    <h1 class="fade-in-up">Carbon Credits Mall</h1>
    <p class="fade-in-up delay-1">Exchange your hard-earned carbon credits for eco-friendly rewards and exclusive benefits.</p>
  </div>
</header>

<div class="container">
  <div class="user-credits ios-depth-effect ios-shine-effect fade-in-up delay-2">
    <div class="row">
      <div class="col-md-8">
        <h2>Your Carbon Credits</h2>
        <div class="credits-amount"><span id="userPoints">Loading...</span></div>
        <p>Use your credits to redeem these amazing eco-friendly products and rewards.</p>
      </div>
      <div class="col-md-4 d-flex align-items-center justify-content-center">
        <a href="pthis.html" class="btn btn-light btn-lg">View History</a>
      </div>
    </div>
  </div>
  
  <div class="section-title-container fade-in-up delay-3">
    <h2 class="section-title">Available Rewards</h2>
  </div>
  
  <div id="loading" class="loading-spinner">
    <div class="ios-loader">
      <div class="ios-loader-ring"></div>
      <div class="ios-loader-dots">
        <div class="ios-loader-dot"></div>
        <div class="ios-loader-dot"></div>
        <div class="ios-loader-dot"></div>
      </div>
      <div class="ios-loader-text">加载商品中...</div>
      <!-- 添加气泡效果 -->
      <div class="bubble" style="left: 20%; animation-delay: 0s;"></div>
      <div class="bubble" style="left: 40%; animation-delay: 1s;"></div>
      <div class="bubble" style="left: 60%; animation-delay: 0.5s;"></div>
      <div class="bubble" style="left: 80%; animation-delay: 1.5s;"></div>
    </div>
  </div>
  
  <div id="productsList">
    <!-- Products will be dynamically loaded here -->
  </div>
</div>

<!-- Theme toggle button -->
<div class="theme-toggle" id="themeToggle">
  <i class="fas fa-moon"></i>
</div>

<!-- 页脚 -->
<div id="footer-placeholder"></div>

  <!-- Load Turnstile Manager FIRST -->
  <script src="js/turnstileManager.js"></script> 

  <script>
  // Global variable specific to this page's logic
  var currentProductIdToExchange = null;
  var exchangeModalWidgetId = null; // Keep track of the widget ID specific to this modal
  
  // Theme toggling functionality
  document.addEventListener('DOMContentLoaded', function() {
    // 创建加载动画气泡效果
    function createBubbles() {
      const loader = document.querySelector('.ios-loader');
      if (loader) {
        setInterval(() => {
          const bubble = document.createElement('div');
          bubble.classList.add('bubble');
          bubble.style.left = Math.floor(Math.random() * 100) + '%';
          bubble.style.animationDuration = (Math.random() * 2 + 2) + 's';
          loader.appendChild(bubble);
          
          // 动画结束后移除气泡
          setTimeout(() => {
            bubble.remove();
          }, 3000);
        }, 300);
      }
    }
    
    createBubbles();
    
    const themeToggle = document.getElementById('themeToggle');
    const body = document.body;
    const icon = themeToggle.querySelector('i');
    
    // Check if user has a saved preference
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      body.className = savedTheme;
      updateIcon(savedTheme);
    }
    
    themeToggle.addEventListener('click', () => {
      if (body.classList.contains('auto-theme')) {
        body.classList.remove('auto-theme');
        body.classList.add('dark-theme');
        localStorage.setItem('theme', 'dark-theme');
      } else if (body.classList.contains('dark-theme')) {
        body.classList.remove('dark-theme');
        body.classList.add('light-theme');
        localStorage.setItem('theme', 'light-theme');
      } else {
        body.classList.remove('light-theme');
        body.classList.add('auto-theme');
        localStorage.setItem('theme', 'auto-theme');
      }
      
      updateIcon(body.className);
    });
    
    function updateIcon(theme) {
      if (theme === 'dark-theme') {
        icon.className = 'fas fa-sun';
      } else if (theme === 'light-theme') {
        icon.className = 'fas fa-adjust';
      } else {
        icon.className = 'fas fa-moon';
      }
    }
  });
  
    $(document).ready(function () {
    console.log('Document ready, initializing Turnstile components');
    
    // --- Initial Checks & Setup ---
    var token = localStorage.getItem('token');
    var uid = localStorage.getItem('userId');
    
    if (!token || !uid) {
      $('#userPoints').text('未登录');
      showAlert('请先登录。', 'warning', function() {
        window.location.href = 'index.html';
      });
      return; // Stop further execution if not logged in
    }
    
    // Fetch user points
    fetchUserPoints(); 
    
    // Ensure the confirmation modal HTML exists or create it
    if (!document.getElementById('exchangeConfirmModal')) {
      console.log('Modal not found on ready, creating it');
      createConfirmationModal(); // Use a dedicated function
    }
    
    // --- Event Bindings ---
    
    // Exchange button click handler
    $(document).on('click', '.exchange-btn', function(e) {
      e.preventDefault();
      console.log('Exchange button clicked');
      
      // Store product info
      currentProductIdToExchange = $(this).data('id');
      var productName = $(this).closest('.product-card').find('.product-title').text();
      var productPrice = $(this).closest('.product-card').find('.price-tag').text();
      
      console.log('Product ID:', currentProductIdToExchange, 'Name:', productName, 'Price:', productPrice);
      
      // Update modal contents
      $('#confirmProductName').text(productName);
      $('#confirmProductPrice').text(productPrice);
      
      // Check if modal exists before showing (redundant check, but safe)
      if (!document.getElementById('exchangeConfirmModal')) {
        console.error('Modal not found before showing!');
        showAlert('Error initializing exchange dialog', 'error');
        return;
      }
      
      // Show the modal
      try {
        $('#exchangeConfirmModal').modal('show');
        console.log('Modal shown successfully');
      } catch (err) {
        console.error('Error showing modal:', err);
      }
    });
    
    // Modal shown event: Render Turnstile using the manager
    $(document).on('shown.bs.modal', '#exchangeConfirmModal', async function () { // Make handler async
      console.log('[shown.bs.modal] Event triggered for #exchangeConfirmModal');
      
      // No need to check for container here, manager does it after delay
      console.log('[shown.bs.modal] Requesting widget render from turnstileManager...');
      
      // Define callbacks for this specific widget instance
      const widgetOptions = {
          callback: function(token) {
              console.log('[Turnstile] Exchange Modal Success callback. Token received.');
              $('#confirmExchangeBtn').prop('disabled', false);
          },
          'expired-callback': function() {
              console.log('[Turnstile] Exchange Modal Expired callback.');
              $('#confirmExchangeBtn').prop('disabled', true);
          },
          'error-callback': function(errorCode) {
              console.error('[Turnstile] Exchange Modal Error callback. Code:', errorCode);
              $('#confirmExchangeBtn').prop('disabled', true);
              showAlert(`Verification error (${errorCode}). Please try again.`, 'error');
          }
      };
      
      // Render the widget using the manager
      exchangeModalWidgetId = await turnstileManager.renderWidget('#turnstile-exchange-widget', widgetOptions, 300); // Use 300ms delay
      
      if (exchangeModalWidgetId) {
          console.log('[shown.bs.modal] Widget render requested successfully. ID:', exchangeModalWidgetId);
          // Ensure button is disabled initially after render request
           $('#confirmExchangeBtn').prop('disabled', true); 
      } else {
          console.error('[shown.bs.modal] Failed to render widget via manager.');
          showAlert('Error loading verification widget. Please close the dialog and try again.', 'error');
      }
    });
    
    // Confirm button click handler
    $(document).on('click', '#confirmExchangeBtn', function() {
      console.log('Confirm exchange button clicked');
      var token = localStorage.getItem('token');
      
      // Get Turnstile response using the manager
      var turnstileResponse = null;
      if (exchangeModalWidgetId) {
          turnstileResponse = turnstileManager.getResponse(exchangeModalWidgetId);
          console.log('Got Turnstile response via manager:', !!turnstileResponse);
      } else {
          console.warn('Cannot get Turnstile response: exchangeModalWidgetId is null.');
      }
      
      // Rest of the validation and AJAX call...
      if (!currentProductIdToExchange) {
        showAlert('Error: Product ID not found.', 'error');
        return;
      }
      
      if (!turnstileResponse) {
        showAlert('Please complete the verification.', 'warning');
        return;
      }
      
      console.log('Proceeding with exchange, product ID:', currentProductIdToExchange);
      exchangeProduct(currentProductIdToExchange, token, turnstileResponse);
      $('#exchangeConfirmModal').modal('hide');
    });
    
    // Modal hidden event: Clean up Turnstile using the manager
    $(document).on('hidden.bs.modal', '#exchangeConfirmModal', function () {
      console.log('Modal hidden, cleaning up Turnstile widget ID:', exchangeModalWidgetId);
      if (exchangeModalWidgetId) {
          turnstileManager.removeWidget(exchangeModalWidgetId); 
          exchangeModalWidgetId = null; // Reset the ID for this page
      }
    });
    
    // --- Initial Data Fetch ---
    fetchProducts(); // Fetch products after setting up handlers
  });

  // Function to create the modal HTML dynamically
  function createConfirmationModal() {
    const modalHTML = `
    <div class="modal fade" id="exchangeConfirmModal" tabindex="-1" role="dialog" aria-labelledby="exchangeConfirmModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content ios-modal-content">
          <div class="modal-header ios-modal-header">
            <h5 class="modal-title" id="exchangeConfirmModalLabel">Confirm Exchange</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body ios-modal-body">
            <p>Are you sure you want to exchange <strong id="confirmProductPrice"></strong> credits for <strong id="confirmProductName"></strong>?</p>
            <!-- Turnstile Widget Container -->
            <div id="turnstile-exchange-widget" style="margin-top: 15px; margin-bottom: 15px;">
              <!-- Turnstile will render here -->
            </div>
            <small class="text-muted">Please complete the verification below.</small>
          </div>
          <div class="modal-footer ios-modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
            <button type="button" class="btn btn-primary" id="confirmExchangeBtn" disabled>Confirm Exchange</button> 
          </div>
        </div>
      </div>
    </div>`;
    $('body').append(modalHTML);
    console.log('Modal HTML appended to body by createConfirmationModal');
  }
  
  // Modify exchangeProduct to accept and send the turnstile token
  function exchangeProduct(productId, token, turnstileResponse) {
      $.ajax({
        type: 'POST',
        url: 'exchange_product.php',
      contentType: 'application/json',
      data: JSON.stringify({ 
        productId: productId, 
        token: token,
        'cf-turnstile-response': turnstileResponse // Add turnstile token
      }),
        dataType: 'json',
        success: function (response) {
          if (response.success) {
          // Use response.message for success too, if available, or a default
          showAlert(response.message || 'Exchange successful!', 'success');
          // 更新用户积分和产品列表
          fetchUserPoints(); 
          fetchProducts();
          } else {
          // Use response.message directly for failure
          showAlert(response.message || 'Exchange failed. Please try again.', 'error');
        }
      },
      error: function (jqXHR, textStatus, errorThrown) {
          console.error("AJAX Error exchanging product:", textStatus, errorThrown);
         // Use a generic error message for AJAX failures
         showAlert('Failed to connect to server for exchange. Please try again later.', 'error');
      }
    }); // Ensure correct closing
    }

    function fetchUserPoints() {
    var uid = localStorage.getItem('userId')
    var token = localStorage.getItem('token')
      $.ajax({
        type: 'POST',
        url: 'get_user_points.php',
      data: {
        uid: uid,
        token: token
      },
        dataType: 'json',
        success: function (response) {
          if (response.success) {
          $('#userPoints').text(response.userPoints)
          } else {
          console.error('Error getting user points:', response.message)
        }
      },
      error: function () {
        console.error('AJAX请求失败')
      }
    })
  }

  function fetchProducts() {
    var token = localStorage.getItem('token')
      $('#loading').show() // 显示加载动画
      $.ajax({
        type: 'POST',
        url: 'product.php',
      data: {
        token: token
      },
        dataType: 'json',
        success: function (response) {
          $('#loading').hide() // 隐藏加载动画
          if (response.success) {
          displayProducts(response.products)
          } else {
          // Use response.message directly
          showAlert(response.message || 'Failed to load products.', 'error'); 
          $('#productsList').html(''); // Clear the list on error
          }
        },
      error: function (jqXHR, textStatus, errorThrown) {
          $('#loading').hide() // 隐藏加载动画
          console.error("AJAX Error fetching products:", textStatus, errorThrown);
          // Use a generic error message for AJAX failures
          showAlert('Failed to connect to server to fetch products. Please try again later.', 'error');
        $('#productsList').html(''); // Clear the list on error
      }
    })
  }

  function displayProducts(products) {
    var productsHtml = ''
    if (products.length === 0) {
      $('#productsList').html('<div class="alert alert-info">No products available at the moment.</div>')
      return
    }

    // 添加动画效果的类
    var animationClasses = ['fade-in-up delay-2', 'fade-in-up delay-3', 'fade-in-up delay-4'];

    // 创建每行的产品列表
    var productsRow = '<div class="row">'
    products.forEach(function (product, index) {
      // 每行显示3个产品
      if (index > 0 && index % 3 === 0) {
        productsRow += '</div><div class="row mt-4">'
      }
      
      // 轮换使用动画类
      var animationClass = animationClasses[index % animationClasses.length];

      productsRow += `
        <div class="col-md-4 mb-4">
          <div class="product-card ios-hover-effect ${animationClass}">
            <img src="${product.image_path}" alt="${product.name}" class="product-img">
            <div class="product-body">
              <h3 class="product-title">${product.name}</h3>
              <p class="product-description">${product.description}</p>
              <div class="product-price">
                <span class="price-tag">${product.points_required} Credits</span>
                <button class="exchange-btn" data-id="${product.id}">Exchange</button>
              </div>
              <div class="stock">Stock: ${product.stock}</div>
            </div>
          </div>
        </div>
      `
    })
    productsRow += '</div>'
    $('#productsList').html(productsRow);
  }
  </script>
</body>
</html>
